﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using CommonLib;

namespace DbLayer
{
    public class DbProxy : IDbProxy
    {
        private static void AddArticleWords(Articles articleDb, IEnumerable<Words> dbWords, IDictionary<string, int> words, DbBridge db)
        {
            foreach (var dbWord in dbWords)
            {
                if (!words.ContainsKey(dbWord.WordText))
                    continue;

                var aw = new ArticleWords { Articles = articleDb, Words = dbWord, WordCount = words[dbWord.WordText] };

                db.AddToArticleWords(aw);
            }

            db.SaveChanges();
        }

        private static List<Words> AddWords(ICollection<string> words, DbBridge db)
        {
            return db.AddWords(words, null);
        }

        private static void AddAuthorArticle(Articles articleD, Authors author, DbBridge db)
        {
            db.AddAuthorArticle(articleD, author, null);
        }

        private static Authors AddAuthor(string authorName, DbBridge db)
        {
            return db.AddToAuthors(authorName);
        }

        private static Articles AddArticle(string title, DateTime date, string articleText, string articleUrl, DbBridge db)
        {
            var article = new Articles
                              {
                                  ArticleTitle = title,
                                  ArticleText = articleText,
                                  ArticleUrl = articleUrl,
                                  ArticleDate = date
                              };

            db.AddToArticles(article);

            return article;
        }

        #region IDbProxy Members

        public IDbProxy CreateInstance()
        {
            throw new NotImplementedException();
        }

        public void AddArticleDb(WordStatArticle article)
        {
            var bridge = new DbBridge();

            bridge.AddArticleDb(article);
        }

        Dictionary<string, int> IDbProxy.GetAllWordsData(int page, int itemOnPages, bool sortByName, string source = null)
        {
            IDbProxy bridge = new DbBridge();

            return bridge.GetAllWordsData(page, itemOnPages, true, source);
        }

        IDictionary<WordStatArticle, int> IDbProxy.GetArticles(string wordText, string currentSource)
        {
            var bridge = new DbBridge();

            return bridge.GetArticles(wordText, currentSource);
        }

        #endregion

        public List<string> GetAllSoyurces()
        {
            var bridge = new DbBridge();

            return bridge.GetAllSoyurces();
        }
    }
}
